//
//  PictureBrowser.swift
//  01MicroBlog
//
//  Created by Apple on 15/8/9.
//  Copyright © 2015年 heima. All rights reserved.
//

import UIKit
import SVProgressHUD

class PictureBrowserController: UIViewController {

    // 这里不需要加问号或进行初始化，因为初始化方法里面已经给这两个属性赋值了
    var pictURLs:[NSURL]
    var indexPath:NSIndexPath
    
    init(pictURLs:[NSURL], indexPath:NSIndexPath) {
        self.pictURLs = pictURLs
        self.indexPath = indexPath
        
        // 视图控制器的默认创建方式
        super.init(nibName: nil, bundle: nil)
    }
    
    override func viewDidLoad() {
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
       
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func loadView() {
        var screenBounds = UIScreen.mainScreen().bounds
        screenBounds.size.width = screenBounds.size.width + 20
        
        view = UIView(frame: screenBounds)
       
        setupUI()
    }
    
    private func setupUI() {
        // 1.添加控件
        view.addSubview(collectionView)
        view.addSubview(closeBtn)
        view.addSubview(saveBtn)
        
        // 2.设置约束
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        closeBtn.translatesAutoresizingMaskIntoConstraints = false
        saveBtn.translatesAutoresizingMaskIntoConstraints = false
        
        let dict = ["collectionView": collectionView, "closeBtn": closeBtn, "saveBtn":saveBtn]
        
        collectionView.frame = view.bounds
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[closeBtn(30)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[saveBtn(30)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[closeBtn(100)]-(>=0)-[saveBtn(100)]-28-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        
        // 3.添加监听方法
        closeBtn.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        saveBtn.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 4.设置独立控件属性
        setupCollectionView()
    }
    
    private func setupCollectionView() {
        // 1.注册cell
        collectionView.registerClass(PictureBrowserCell.self, forCellWithReuseIdentifier: reuseId)
        // 2.设置数据源
        collectionView.dataSource = self
        
       let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = view.bounds.size
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        flowLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView.pagingEnabled = true
    }
    
    // MARK: - 监听按钮的点击
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func save() {
        // 获取图片
        let indexPath = collectionView.indexPathsForVisibleItems().last
        let cell = collectionView.cellForItemAtIndexPath(indexPath!) as! PictureBrowserCell
        
        guard let image = cell.imageView.image else {
            SVProgressHUD.showErrorWithStatus("照片不存在")
            return
        }

        // 调用方法
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
        
    }

    // OC中的方法
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    
    // Swift中的方法
    func image(image:UIImage, didFinishSavingWithError error:NSError?, contextInfo:AnyObject?) {

        if error != nil {
            SVProgressHUD.showErrorWithStatus("保存失败")
        } else {
            SVProgressHUD.showSuccessWithStatus("保存成功")
        }
    }
    
    // MARK: - 隐藏控制器的视图
    func hidesViewControl(hidden:Bool) {
        collectionView.backgroundColor = hidden ? UIColor.clearColor() : UIColor.blackColor()
        saveBtn.hidden = hidden
        closeBtn.hidden = hidden
    }
    
    // 获取正在显示的cell索引
    func currentIndexPath() -> NSIndexPath {
        return collectionView.indexPathsForVisibleItems().last!
    }
    
    /// 当前显示的图像视图
    func currentImageView() -> UIImageView {
        let cell = collectionView.cellForItemAtIndexPath(currentIndexPath()) as! PictureBrowserCell
        
        return cell.imageView
    }
 
    // MARK: - 懒加载控件
    private lazy var collectionView:UICollectionView = UICollectionView(frame: UIScreen.mainScreen().bounds, collectionViewLayout: UICollectionViewFlowLayout())
    
    private lazy var closeBtn:UIButton = UIButton(title:"关闭", textColor: UIColor.darkGrayColor(), textFont: 14, backgroundColor: UIColor.lightGrayColor())
    
    private lazy var saveBtn:UIButton = UIButton(title: "保存", textColor: UIColor.darkGrayColor(), textFont: 14, backgroundColor: UIColor.lightGrayColor())
    
    var zoomRate:CGFloat = 1
}


// MARK: - 数据源方法
let reuseId = "PictureBrowser_cell"

extension PictureBrowserController: UICollectionViewDataSource, PictureBrowserCellDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictURLs.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
       let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseId, forIndexPath: indexPath) as! PictureBrowserCell
        cell.resetScrollView()
//        cell.backgroundColor = UIColor.blackColor()
        cell.imageUrl = pictURLs[indexPath.row]
        cell.pictureDelegate = self
        
        return cell
    }
    
    // 缩放进行中
    func pictureZooming(rate: CGFloat) {
        zoomRate = rate

        // 缩小操作时，隐藏背景视图
        if rate < 1 {
            hidesViewControl(true)
            
            // 开始转场
            startInteractiveTransition(self)
        } else {
            view.transform = CGAffineTransformIdentity
            view.alpha = 1
        }
        
        
        startInteractiveTransition(self)
    }
    
    // 结束缩放
    func pictureEndZooming() {
        if zoomRate < 0.8 {
            completeTransition(true)
        } else {
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.view.transform = CGAffineTransformIdentity
                self.view.alpha = 1
                }, completion: { (_) -> Void in
                    self.zoomRate = 1
                    self.hidesViewControl(false)
            })
        }
        
        
        print("结束缩放")
    }
}

// MARK: - 遵守交互转场协议
extension PictureBrowserController: UIViewControllerInteractiveTransitioning, UIViewControllerContextTransitioning{
    
    // 开始交互转场
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        view.transform = CGAffineTransformMakeScale(zoomRate, zoomRate)
        view.alpha = zoomRate
    }
    
    // 结束转场，关闭控制器
    func completeTransition(didComplete: Bool) {
        dismissViewControllerAnimated(true, completion: nil)
    }

    func containerView() -> UIView? { return view}

    func isAnimated() -> Bool { return true }
    
    func isInteractive() -> Bool { return true}
    
    func transitionWasCancelled() -> Bool { return true}
    
    func presentationStyle() -> UIModalPresentationStyle { return UIModalPresentationStyle.Custom}

    func updateInteractiveTransition(percentComplete: CGFloat) {}
    func finishInteractiveTransition(){}
    func cancelInteractiveTransition(){}

    func viewControllerForKey(key: String) -> UIViewController? {
        return self
    }

    func viewForKey(key: String) -> UIView? {
        return view
    }

    func targetTransform() -> CGAffineTransform {
        return CGAffineTransformIdentity
    }
    func initialFrameForViewController(vc: UIViewController) -> CGRect {
        return CGRectZero
    }
    func finalFrameForViewController(vc: UIViewController) -> CGRect {
        return CGRectZero
    }
}
